import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import threading
import music
import user
import map

app = FastAPI(title="music_service_back", version="1.1")

# CORS 配置
origins = [
    # 开发环境
    "http://localhost:3000",
    "http://127.0.0.1:3000",
    "http://192.168.1.11:3000",
    "http://172.30.169.1:3000",

    # 移动端和 Capacitor
    "capacitor://localhost",
    "http://localhost",
    "ionic://localhost",

    # 生产环境域名
    "https://192.168.1.11",
    "https://172.30.169.1",

    # Android 应用
    "file://",

    # 如果需要，可以临时允许所有（不推荐生产环境）
    # "*"
]

# 添加 CORS 中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"],
    allow_headers=[
        "Content-Type",
        "Authorization",
        "Accept",
        "Origin",
        "X-Requested-With",
        "X-CSRF-Token",
        "Access-Control-Request-Headers",
        "Access-Control-Request-Method",
        "Accept-Encoding",
        "Accept-Language",
        "Cache-Control",
        "Connection",
        "Host",
        "Pragma",
        "Referer",
        "User-Agent",
        "X-Device-ID",
        "X-Platform"
    ],
    expose_headers=[
        "Content-Range",
        "X-Total-Count",
        "X-Request-ID",
        "X-Response-Time"
    ],
    max_age=600  # 预检请求缓存时间（秒）
)


def ipv4():
    uvicorn.run(app=app, host="0.0.0.0", port=8000)


def ipv6():
    uvicorn.run(app=app, host="::", port=8000)


app.include_router(music.router, prefix="", tags=["music"])
app.include_router(user.router, prefix="", tags=["user"])
app.include_router(map.router, prefix="", tags=["map"])

if __name__ == "__main__":
    '''t1 = threading.Thread(target=ipv4, args=())
    t2 = threading.Thread(target=ipv6, args=())
    t1.start()
    t2.start()
    t1.join()
    t2.join()'''
    uvicorn.run(app=app, host="0.0.0.0", port=8000)
